package com.example.clxy.service.impl;

import com.example.clxy.dao.AdjustscheduleMapper;
import com.example.clxy.dao.ScheduleMapper;
import com.example.clxy.dao.ScheduleStudentGxMapper;
import com.example.clxy.dao.WlclassMapper;
import com.example.clxy.entity.Adjustschedule;
import com.example.clxy.entity.Schedule;
import com.example.clxy.entity.ScheduleStudentGx;
import com.example.clxy.entity.ScheduleStudentGxKey;
import com.example.clxy.result.PageResult;
import com.example.clxy.result.StandardResult;
import com.example.clxy.result.WebRestResult;
import com.example.clxy.result.business.AdjustScheduleResult;
import com.example.clxy.result.business.GradeClassResult;
import com.example.clxy.result.business.PageResult.AdjustSchedulePageResult;
import com.example.clxy.result.business.PageResult.WorkableAdjustSchedulePageResult;
import com.example.clxy.service.AdjustScheduleService;
import com.example.clxy.util.RespUtil;
import com.example.clxy.util.Tools;
import com.example.clxy.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author weichong
 * date 2020-08-05
 * @Description:
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AdjustScheduleServiceImpl implements AdjustScheduleService {

    @Autowired
    private AdjustscheduleMapper adjustscheduleMapper;
    @Autowired
    private ScheduleStudentGxMapper scheduleStudentGxMapper;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private WlclassMapper wlclassMapper;

    @Override
    public WebRestResult addAdjustSchedule( Adjustschedule adjustschedule){
        if(adjustschedule.getStudentid() == null || adjustschedule.getStudentid().isEmpty()){
            return RespUtil.failResp("学生id不能为空!");
        }else if(adjustschedule.getTeacherid() == null ||adjustschedule.getTeacherid().isEmpty()){
            return RespUtil.failResp("老师id不能为空!");
        }else if(adjustschedule.getOldscheduleid() == null || adjustschedule.getOldscheduleid().isEmpty()){
            return RespUtil.failResp("旧排课id不能为空!");
        }else if(adjustschedule.getNewscheduleid() == null || adjustschedule.getNewscheduleid().isEmpty()){
            return RespUtil.failResp("新排课id不能为空!");
        }

        if( adjustscheduleMapper.selectAdjustSchedule( adjustschedule.getStudentid(),adjustschedule.getOldscheduleid(),adjustschedule.getNewscheduleid()) > 0 ){
            return RespUtil.failResp("申请正在审核中,请不要重复申请!");
        }

        if(adjustscheduleMapper.selectDuplicateSchedule(adjustschedule.getStudentid(),adjustschedule.getOldscheduleid()) > 0){
            return RespUtil.failResp("只允许调课一次!");
        }

        adjustschedule.setAdjustclassid(UUIDUtil.randomUUID());
        adjustschedule.setFlag("0");
        adjustschedule.setCreatedTime(new Date());
        adjustschedule.setUpdatedTime(new Date());
        adjustschedule.setAdjuststate("0");
        if(adjustscheduleMapper.insert(adjustschedule)==1){
            return RespUtil.successResp("新增调课申请成功!");
        }
        return RespUtil.failResp("新增调课申请失败!");
    }

    @Override
    public PageResult<AdjustSchedulePageResult> getAdjustSchedule(String teacherid,String studentid, String adjuststate, int page, int pagesize){
        PageResult<AdjustSchedulePageResult> res = new PageResult<>();
        int begin = (page-1) * pagesize;
        int end = pagesize;
        List<AdjustSchedulePageResult> adjustScheduleList = adjustscheduleMapper.getAdjustSchedule(teacherid,studentid,adjuststate,begin,end,pagesize);
        if(adjustScheduleList.size()>0){
            for (AdjustSchedulePageResult a:adjustScheduleList) {
                List<GradeClassResult> gradeClassResultList = wlclassMapper.getClassBySchedule(a.getNewscheduleid());

                String[] newclassname = new String[gradeClassResultList.size()];
                for (int i = 0 ; i < gradeClassResultList.size(); i++) {
                    newclassname[i] = gradeClassResultList.get(i).getClassname();
                }
                a.setNewclassname(newclassname);

            }
            res.setTotal(adjustScheduleList.get(0).getCnt());
            res.setPageCount(adjustScheduleList.get(0).getPage());
            res.setRows(adjustScheduleList);
        }
        res.setResult(WebRestResult.SUCCESS);
        res.setMessage("查询调课申请信息成功");
        return res;

    }

    @Override
    public StandardResult getAdjustByScheduleid(String adjustclassid){
        if(Tools.isEmpty(adjustclassid)){
            return RespUtil.failStandardResult("调课id不能为空!",null);
        }
        AdjustScheduleResult res = adjustscheduleMapper.getAdjustByScheduleid(adjustclassid);
        if(res==null){
            return RespUtil.failStandardResult("调课不存在!",null);
        }
        List<GradeClassResult> gradeClassResultList = wlclassMapper.getClassBySchedule(res.getNewscheduleid());

        String[] newclassname = new String[gradeClassResultList.size()];
        for (int i = 0 ; i < gradeClassResultList.size(); i++) {
            newclassname[i] = gradeClassResultList.get(i).getClassname();
        }
        res.setNewclassname(newclassname);
        List<AdjustScheduleResult> results = new ArrayList<>();
        results.add(res);
        return RespUtil.successStandardResult("查询成功!",results);
    }


    @Override
    public PageResult<WorkableAdjustSchedulePageResult> getWorkableAdjustSchedule(String scheduleid, int page, int pagesize){
        PageResult<WorkableAdjustSchedulePageResult> res = new PageResult<>();
        if(scheduleid == null || scheduleid.isEmpty()){
            res.setMessage("调课id不能为空");
            return res;
        }
        int begin = (page-1) * pagesize;
        int end = pagesize;

        Schedule schedule =  scheduleMapper.selectByPrimaryKey(scheduleid);
        if(schedule == null){
            res.setMessage("调课不存在");
            return res;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate =  df.format(new Date());
        String startDate =  df.format(new Date(schedule.getStartdate().getTime() - 7 * 24 * 60 * 60 * 1000L));
        String endDate =  df.format(new Date(schedule.getStartdate().getTime() + 7 * 24 * 60 * 60 * 1000L));
        List<WorkableAdjustSchedulePageResult> adjustScheduleList = adjustscheduleMapper.getWorkableAdjustSchedule(scheduleid, nowDate, startDate, endDate,begin,end,pagesize);
        if(adjustScheduleList.size()>0){
            for (WorkableAdjustSchedulePageResult w:adjustScheduleList) {
                List<GradeClassResult> gradeClassResultList = wlclassMapper.getClassBySchedule(w.getScheduleid());
                String[] classid = new String[gradeClassResultList.size()];
                String[] classname = new String[gradeClassResultList.size()];
                for (int i = 0; i < gradeClassResultList.size(); i++) {
                    classid[i] = gradeClassResultList.get(i).getClassid();
                    classname[i] = gradeClassResultList.get(i).getClassname();
                }
                w.setClassid(classid);
                w.setClassname(classname);
            }

            res.setTotal(adjustScheduleList.get(0).getCnt());
            res.setPageCount(adjustScheduleList.get(0).getPage());
            res.setRows(adjustScheduleList);
        }
        res.setResult(WebRestResult.SUCCESS);
        res.setMessage("查询可调课信息成功");
        return res;
    }



    @Override
    public WebRestResult updateAdjustSchedule( Adjustschedule adjustschedule){
        adjustschedule.setUpdatedTime(new Date());
        if(adjustschedule.getAdjustclassid() == null|| adjustschedule.getAdjustclassid().isEmpty()){
            return RespUtil.failResp("调课id不能为空!");
        }
        //            获取调课申请全部信息
        Adjustschedule adjustinfo =  adjustscheduleMapper.selectByPrimaryKey(adjustschedule.getAdjustclassid());
        if(adjustinfo.getAdjuststate().equals(adjustschedule.getAdjuststate())){
            return RespUtil.failResp("请勿重复提交!");
        }
        if(!adjustinfo.getAdjuststate().equals("0")){
            return RespUtil.failResp("该申请已处理!");
        }
        if(adjustschedule.getAdjuststate().equals("1") ){
            Date now = new Date();
//          新排课或旧排课的开始时间如果小于等于当前时间,直接拒绝
            Schedule newschedule = scheduleMapper.selectByPrimaryKey(adjustinfo.getNewscheduleid());
            Schedule oldschedule = scheduleMapper.selectByPrimaryKey(adjustinfo.getOldscheduleid());
            if( newschedule.getStartdate().getTime() - now.getTime() <= 1000 * 60 * 60 * 24||
                    oldschedule.getStartdate().getTime() - now.getTime() <= 1000 * 60 * 60 * 24){
                adjustschedule.setAdjuststate("2");
                adjustscheduleMapper.updateByPrimaryKeySelective(adjustschedule);
                return RespUtil.failResp("新排课或旧排课的开始时间小于等于当前时间,直接拒绝");
            }
            //获取学生旧排课关系表信息
            ScheduleStudentGxKey scheduleStudentGxKey = new ScheduleStudentGxKey();
            scheduleStudentGxKey.setScheduleid(adjustinfo.getOldscheduleid());
            scheduleStudentGxKey.setStudentid(adjustinfo.getStudentid());
            ScheduleStudentGx scheduleStudentGx =  scheduleStudentGxMapper.selectByPrimaryKey(scheduleStudentGxKey);
            scheduleStudentGx.setFlag("1");
            scheduleStudentGxMapper.updateByPrimaryKeySelective(scheduleStudentGx);
            //删除旧排课信息,新增新排课信息
//            scheduleStudentGxMapper.deleteByPrimaryKey(scheduleStudentGxKey);
            scheduleStudentGx.setScheduleid(adjustinfo.getNewscheduleid());
            scheduleStudentGx.setFlag("0");
            scheduleStudentGx.setCreatedTime(new Date());
            scheduleStudentGx.setUpdatedTime(new Date());
            scheduleStudentGxMapper.insert(scheduleStudentGx);

            newschedule.setCurnums(newschedule.getCurnums() == null ? 1:newschedule.getCurnums() +1);
            oldschedule.setCurnums((oldschedule.getCurnums() == null || oldschedule.getCurnums() == 0)? 0:oldschedule.getCurnums() -1);
            scheduleMapper.updateByPrimaryKeySelective(newschedule);
            scheduleMapper.updateByPrimaryKeySelective(oldschedule);
        }

        if(adjustscheduleMapper.updateByPrimaryKeySelective(adjustschedule) == 1){
            return RespUtil.successResp("审批成功");
        }
        return RespUtil.failResp("审批失败");
    }

}
